import { getPipelineTemplateConfig } from '@/api/operationManagement';
import { storageGenerator } from '@/utils/cache';
import { defineStore } from 'pinia';
import { PipelineOperationTypeCode } from '@/enums/pipelineEnum';

export const usePipelineTemplateStore = defineStore('pipelineTemplate', {
  state: (): OperationManagement.PipelineTemplateConfig => {
    return {
      tabsName: '', // 页面标签名称
      taskList: <Pipeline.Task[]>[], // 流程编排数据
      baseInfo: <OperationManagement.BaseInfo>{}, // 基础信息数据
      variableSettingList: <Pipeline.VariableSetting[]>[], // 变量数据
      actionType: PipelineOperationTypeCode.add, //当前操作类型
    };
  },
  getters: {
    getFlowChoreographyData(): Pipeline.Task[] {
      return this.taskList ?? [];
    },
    getBaseInfoData(): OperationManagement.BaseInfo {
      return this.baseInfo ?? {};
    },
    getVariablesData(): Pipeline.VariableSetting[] {
      return this.variableSettingList ?? [];
    },
    getActionTypeData(): string {
      return this.actionType ?? PipelineOperationTypeCode.add;
    },
    getAllData(): OperationManagement.PipelineTemplateConfig {
      return {
        taskList: this.taskList,
        baseInfo: this.baseInfo, // 基础信息数据
        variableSettingList: this.variableSettingList, // 变量数据
      };
    },
  },
  actions: {
    setTabsName(tabsName: string) {
      this.tabsName = tabsName;
    },
    setFlowChoreographyData(info: any) {
      this.taskList = [...info];
    },
    setBaseInData(info: any) {
      this.baseInfo = { ...info };
    },
    setVariablesData(info: any) {
      this.variableSettingList = [...info];
    },
    async fetchPipelineTemplateConfigData(code: string) {
      const data = await getPipelineTemplateConfig(code);
      if (data) {
        this.taskList = data.taskList;
        this.baseInfo = data.baseInfo || {};
        this.variableSettingList = data.variableSettingList || [];
      }
    },
    setActionTypeData(type: string) {
      this.actionType = type;
    },
    clearData() {
      this.baseInfo = {} as OperationManagement.BaseInfo;
      this.taskList = [];
      this.actionType = PipelineOperationTypeCode.add;
      this.variableSettingList = [];
    },
  },
  // 配置是否存入本地缓存，默认存入sessionStorage，具体使用参考文档 https://seb-l.github.io/pinia-plugin-persist/
  persist: {
    enabled: true,
    strategies: [{ storage: storageGenerator('pipelineTemplate'), paths: ['pipelineTemplate'] }],
  },
});
